#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###----------1、文件说明----------###
'''
* 说明：提取word中的图片到一个目录中
* 时间：2024-11-02 15:57:27
* 文件：
* 作者：Smile
* 版本：1.0
* 备注：
'''
import os, sys
from PySide2.QtWidgets import QMainWindow, QApplication, QWidget
from PySide2.QtWidgets import QLineEdit, QPushButton, QTextEdit
from PySide2.QtWidgets import QHBoxLayout, QVBoxLayout
# 文件选择函数所需要的库
from PySide2.QtWidgets import QFileDialog,QDialog
from PySide2.QtCore import QEventLoop, QTimer
import qdarkstyle
from qdarkstyle import LightPalette # 颜色主题
import pywinstyles  # 窗口样式
import qtawesome as qta # 图标库
from loguru import logger as log
import zipfile
import shutil

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("界面例程")
        self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5', palette=LightPalette())  )
        self.path = []
        self.initGUI()
        self.setWindowIcon(qta.icon('fa5s.yin-yang', color='brown', color_active='orange'))
        self.resize(800, 600)

    def initGUI(self):
        self.widget =  QWidget(self)
        layout = QVBoxLayout(self.widget)
        # 第一行
        self.lineedit = QLineEdit(self.widget)
        self.lineedit.setText(str(self.path))
        self.lineedit.setReadOnly(True)
        self.fileselect = QPushButton("文件选择", self.widget)
        self.fileselect.clicked.connect(lambda : self.getFileName(1))
        self.anyfileselect = QPushButton("多文件选择", self.widget)
        self.anyfileselect.clicked.connect(lambda : self.getFileName(3))
        self.pathselect = QPushButton("目录选择", self.widget)
        self.pathselect.clicked.connect(lambda : self.getFileName(2))
        linelayout = QHBoxLayout(self.widget)
        linelayout.addWidget(self.lineedit)
        linelayout.addWidget(self.fileselect)
        linelayout.addWidget(self.anyfileselect)
        linelayout.addWidget(self.pathselect)
        # 第二行
        self.textedit = QTextEdit(self.widget)
        layout.addLayout(linelayout)
        layout.addWidget(self.textedit)
        # 第三行
        self.startbutton = QPushButton("运行程序", self.widget)
        layout.addWidget(self.startbutton)
        # 设置主要显示区
        self.setCentralWidget(self.widget)

        self.startbutton.clicked.connect(self.run)

    def fileSelect(self, filemode=0):
        '''
        filemode: 0-文件的名称，无论它是否存在 1-单文件模式 2-目录模型 3-多文件模式
        '''
        fileNames = []
        fileDialog = QFileDialog(self)
        fileDialog.setViewMode(QFileDialog.Detail)

        if filemode == 1:
            fileDialog.setFileMode(QFileDialog.ExistingFile)
        elif filemode == 2:
            fileDialog.setFileMode(QFileDialog.Directory)
        elif filemode == 3:
            fileDialog.setFileMode(QFileDialog.ExistingFiles)
        else:
            fileDialog.setFileMode(QFileDialog.AnyFile)

        fileDialog.setNameFilter("file(*.*);;all file(*)")
        ret = fileDialog.exec_()
        if ret == QDialog.Accepted:
            fileNames = fileDialog.selectedFiles()
        return fileNames

    def getFileName(self, mode=1):
        print(self.lineedit.text())
        self.path = self.fileSelect(filemode=mode)
        self.lineedit.setText(str(self.path))

    def run(self):
        log.info("Start Program")
        # self.path = list(self.lineedit.text())
        os.makedirs("images", exist_ok=True)
        for name in self.path:
            print(name)
            # 处理文件
            if os.path.isfile(name):
                self.getPhoto(name, "images")
            # 处理目录
            if os.path.isdir(name):
                for root, dirs, files in os.walk(name):
                    # 处理所有文件
                    for file in files:
                        if not file.endswith("docx"):
                            continue
                        self.getPhoto(os.path.join(root, file), "images")

    def zipfile(self, src, dst):
        # 打开zip文件
        with zipfile.ZipFile(src, 'r') as zip_ref:
            # 解压所有文件到指定文件夹
            zip_ref.extractall(dst)

    def getPhoto(self, src, dst):
        # 提取word中的图片
        # 事件延时代码
        loop = QEventLoop()
        QTimer.singleShot(100, loop.quit)
        loop.exec_()

        self.zipfile(src, "tmp")
        for name in os.listdir(r"tmp//word//media"):
            filesrc = os.path.join(r"tmp//word//media", name)
            filedst = os.path.join(dst, os.path.splitext(os.path.basename(src))[0] + "_" + name)
            print(filesrc, filedst)
            os.rename(filesrc, filedst)
        shutil.rmtree("tmp")



if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    pywinstyles.apply_style(mainWin, "win7")
    mainWin.show()
    sys.exit(app.exec_())
